package handlers

import (
	"fmt"
	"gin-blog/models"
	"gin-blog/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func List(c *gin.Context) {
	id := c.PostForm("id")
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "用户详情-post",
		"data": id,
	})
	return
}
func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	user := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加ok",
	})
	return
}
func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(models.User{}).Count(&count)
	var user []models.User
	models.DB.Offset(offset).Limit(size).Find(&user)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  user,
		"count": count,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Delete(&models.User{}, id).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}
func Det(c *gin.Context) {
	id := c.Query("id")
	var user models.User
	err := models.DB.First(&user, id).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": user,
	})
	return
}
func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user models.User
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名或者密码不能为空",
		})
		return
	}
	err := models.DB.Where("username=?", username).First(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}

	if user.Password != pkg.Md5Srt(password) {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	token, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
	return
}
func UserGetToken(c *gin.Context) {
	uil, _ := c.Get("uid")
	id := c.Query("id")
	fmt.Println("userGetToken方法：获取到uid-", uil)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"uid":  uil,
		"id":   id,
	})
	return
}
